package com.cd.university.controller;

import com.cd.university.common.RestResult;
import com.cd.university.controller.form.RoleForm;
import com.cd.university.controller.form.UserRoleIdForm;
import com.cd.university.db.pojo.Role;
import com.cd.university.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author 陈栋
 * @create 2021/9/15 17:02
 */
@RequestMapping("/role")
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/getRoles")
    @ApiOperation("获得所有的用户角色信息")
    public RestResult getRoles() {
        return RestResult.success("获得所有的角色")
                .put("data",roleService.searchAllRole());
    }

    @PostMapping("/insert")
    @ApiOperation("新增用户角色")
    @PreAuthorize("hasAnyAuthority('管理角色')")
    public RestResult insertRole(@Valid @RequestBody RoleForm form) {
        try {
            Role role = new Role();
            BeanUtils.copyProperties(form, role);
            int roleId = roleService.insertRoleName(role);
            return RestResult.success("新增角色成功")
                    .put("data",roleService.searchAllRole())
                    .put("roleId",roleId);
        }catch (Exception e) {
            e.printStackTrace();
            return RestResult.failure("新增角色失败");
        }
    }

    @GetMapping("/delete/{roleId}")
    @ApiOperation("删除角色")
    @PreAuthorize("hasAnyAuthority('管理角色')")
    public RestResult deleteRole(@PathVariable Integer roleId) {
        try {
            roleService.deleteRole(roleId);
            return RestResult.success("删除角色成功")
                    .put("data",roleService.searchAllRole());
        }catch (Exception e) {
            e.printStackTrace();
            return RestResult.failure("删除角色失败");
        }
    }

    @PostMapping("/update")
    @ApiOperation("修改角色信息")
    @PreAuthorize("hasAnyAuthority('管理角色')")
    public RestResult updateRole(@Valid @RequestBody RoleForm form) {
        try {
            roleService.updateRole(form.getRoleId(), form.getRoleName());
            return RestResult.success("修改角色成功")
                    .put("data",roleService.searchAllRole());
        }catch (Exception e) {
            e.printStackTrace();
            return RestResult.failure("修改角色失败");
        }
    }
}
